<template>
  <div class="system-config" v-loading="loading">

    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本设置" name="basic">
        <div class="container">
          <el-form :model="system" label-width="150px" label-position="right" ref="systemFormRef" :rules="rules">
            <el-form-item label="网站标题" prop="title">
              <el-input v-model="system['title']"/>
            </el-form-item>
            <el-form-item label="控制台标题" prop="admin_title">
              <el-input v-model="system['admin_title']"/>
            </el-form-item>
            <el-form-item label="网站 LOGO" prop="logo">
              <el-input v-model="system['logo']" placeholder="网站LOGO图片">
                <template #append>
                  <el-upload
                      :auto-upload="true"
                      :show-file-list="false"
                      @click="beforeUpload('logo')"
                      :http-request="uploadImg"
                  >
                    <el-icon class="uploader-icon">
                      <UploadFilled/>
                    </el-icon>
                  </el-upload>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="注册赠送算力" prop="init_power">
              <el-input v-model.number="system['init_power']" placeholder="新用户注册赠送算力"/>
            </el-form-item>
            <el-form-item label="邀请赠送算力" prop="invite_power">
              <el-input v-model.number="system['invite_power']" placeholder="邀请新用户注册赠送算力"/>
            </el-form-item>
            <el-form-item label="VIP每日赠送算力" prop="vip_default_day_power">
              <el-input v-model.number="system['vip_default_day_power']" placeholder="VIP用户每日赠送算力"/>
            </el-form-item>
            <el-form-item label="每日赠送算力" prop="daily_power">
              <div class="tip-input-line">
                <el-input v-model.number="system['daily_power']" placeholder="默认值0"/>
                <div class="tip">
                  如果设置0表示不赠送，用户享受完免费算力额度之后就不能再发起对话了。如果设置为N，则系统每天将算力值小于N的用户自动补充到N。注意，此功能要配合XXL-JOB启用。
                </div>
              </div>
            </el-form-item>
            <el-form-item label="MidJourney算力" prop="mj_power">
              <el-input v-model.number="system['mj_power']" placeholder="使用MidJourney画一张图消耗算力"/>
            </el-form-item>
            <el-form-item label="Stable-Diffusion算力" prop="sd_power">
              <el-input v-model.number="system['sd_power']" placeholder="使用Stable-Diffusion画一张图消耗算力"/>
            </el-form-item>
            <el-form-item label="DALL-E-3算力" prop="dall_power">
              <el-input v-model.number="system['dall_power']" placeholder="使用DALL-E-3画一张图消耗算力"/>
            </el-form-item>
            <el-form-item label="开放注册" prop="enabled_register">
              <el-switch v-model="system['enabled_register']"/>
              <el-tooltip
                  effect="dark"
                  content="关闭注册之后只能通过管理后台添加用户"
                  raw-content
                  placement="right"
              >
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="启用敏感词审核" prop="enabled_sensitive_word">
              <el-switch v-model="system['enabled_sensitive_word']"/>
              <el-tooltip
                  effect="dark"
                  content="关闭敏感词审核之后将不会自动启用敏感词审核，如果需要百度的在线审核，请联系作者"
                  raw-content
                  placement="right"
              >
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="启用人机验证" prop="enabled_bot_validate">
              <el-switch v-model="system['enabled_bot_validate']"/>
              <el-tooltip
                  effect="dark"
                  content="关闭人机校验后获取短信或邮件二维码将不会再弹出人机验证框"
                  raw-content
                  placement="right"
              >
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="注册方式" prop="register_ways">
              <el-checkbox-group v-model="system['register_ways']">
                <el-checkbox label="mobile">手机注册</el-checkbox>
                <el-checkbox label="email">邮箱注册</el-checkbox>
                <!--                <el-checkbox label="username">用户名注册</el-checkbox>-->
                <el-checkbox label="wechat">微信注册(必须配置微信公众号)</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!--            <el-form-item label="启用众筹功能" prop="enabled_reward">-->
            <!--              <el-switch v-model="system['enabled_reward']"/>-->
            <!--              <el-tooltip-->
            <!--                  effect="dark"-->
            <!--                  content="如果关闭次功能将不在用户菜单显示众筹二维码"-->
            <!--                  raw-content-->
            <!--                  placement="right"-->
            <!--              >-->
            <!--                <el-icon>-->
            <!--                  <InfoFilled/>-->
            <!--                </el-icon>-->
            <!--              </el-tooltip>-->
            <!--            </el-form-item>-->

            <!--            <div v-if="system['enabled_reward']">-->
            <!--              <el-form-item label="算力单价" prop="power_price">-->
            <!--                <el-input v-model="system['power_price']"-->
            <!--                          placeholder="单位算力的价格，比如设置 0.1 表示捐赠1元钱可以得到10个单位算力"/>-->
            <!--              </el-form-item>-->
            <!--              <el-form-item label="收款二维码" prop="reward_img">-->
            <!--                <el-input v-model="system['reward_img']" placeholder="众筹收款二维码地址">-->
            <!--                  <template #append>-->
            <!--                    <el-upload-->
            <!--                        :auto-upload="true"-->
            <!--                        :show-file-list="false"-->
            <!--                        @click="beforeUpload('reward_img')"-->
            <!--                        :http-request="uploadImg"-->
            <!--                    >-->
            <!--                      <el-icon class="uploader-icon">-->
            <!--                        <UploadFilled/>-->
            <!--                      </el-icon>-->
            <!--                    </el-upload>-->
            <!--                  </template>-->
            <!--                </el-input>-->
            <!--              </el-form-item>-->
            <!--            </div>-->

            <el-form-item label="微信客服二维码" prop="wechat_card_url">
              <el-input v-model="system['wechat_card_url']" placeholder="微信客服二维码">
                <template #append>
                  <el-upload
                      :auto-upload="true"
                      :show-file-list="false"
                      @click="beforeUpload('wechat_card_url')"
                      :http-request="uploadImg"
                  >
                    <el-icon class="uploader-icon">
                      <UploadFilled/>
                    </el-icon>
                  </el-upload>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="订单超时时间" prop="order_pay_timeout">
              <div class="tip-input">
                <el-input v-model.number="system['order_pay_timeout']" placeholder="单位：秒"/>
                <div class="info">
                  <el-tooltip
                      effect="dark"
                      content="系统会定期清理超时未支付的订单<br/>默认值：900秒"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="会员充值说明" prop="order_pay_timeout">
              <div class="tip-input">
                <el-input v-model="system['vip_info_text']" placeholder=""/>
                <div class="info">
                  <el-tooltip
                      effect="dark"
                      content="会员充值页面的充值说明文字"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="默认AI模型" prop="default_models">
              <template #default>
                <div class="tip-input">
                  <el-select
                      v-model="system['default_models']"
                      multiple
                      :filterable="true"
                      placeholder="选择AI模型，多选"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in models"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                  </el-select>
                  <div class="info">
                    <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="新用户注册默认开通的 AI 模型"
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-form-item>

            <el-form-item label="开启聊天上下文">
              <el-switch v-model="system['enable_context']"/>
            </el-form-item>
            <el-form-item label="会话上下文深度">
              <div class="tip-input-line">
                <el-input-number v-model="system['context_deep']" :min="0" :max="10"/>
                <div class="tip">会话上下文深度：在老会话中继续会话，默认加载多少条聊天记录作为上下文。如果设置为
                  0
                  则不加载聊天记录，仅仅使用当前角色的上下文。该配置参数最好设置需要为偶数，否则将无法兼容百度的 API。
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="save('system')">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="文件配置" name="file">
        <div class="container">
          <el-form :model="file" label-position="right" label-width="150px" ref="fileFormRef" :rules="rules">
            <el-alert
                type="warning"
                :closable="false"
                show-icon
                style="margin-bottom: 10px; font-size:14px;">
              <p><b>注意：</b>文件系统切换，如果原来是私有的OSS，没有CDN的话，可能无法访问</p>
            </el-alert>
            <el-form-item label="文件系统">
              <div>
                <el-select v-model="file['config_key']" prop="config_key" placeholder="请选择文件系统" required>
                  <el-option value="OSS" label="OSS" key=1>OSS</el-option>
                  <el-option value="LOCAL" label="本地" key=2>本地</el-option>
                </el-select>
              </div>
            </el-form-item>

            <el-form-item label="访问域名"
                          :required="file['access_base_url'] == 'LOCAL' || file['access_policy'] == '0'"
                          prop="access_base_url">
              <el-input v-model="file['access_base_url']" autocomplete="off"></el-input>
              <div class="tip">
                文件访问域名(一般都是系统的域名)，如果设置oss设置为【私有】或者【CDN域名为空】或者【本地存储】的话，这里不能为空
              </div>
            </el-form-item>

            <template v-if="file['config_key'] == 'LOCAL'">
              <el-form-item label="本地路径" :required="file['config_key'] == 'LOCAL'" prop="local_path">
                <el-input v-model="file['local_path']" autocomplete="off"></el-input>
                <div class="tip">本地路径，注意如果是部署到容器的话是容器路径</div>
              </el-form-item>
            </template>
            <template v-if="file['config_key'] == 'OSS'">
              <el-alert
                  type="success"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 10px; font-size:14px;">
                <p><b>支持服务商：</b>支付Minio、阿里云、腾讯云、七牛云、百度云等支持S3协议的云OSS</p>
              </el-alert>
              <el-form-item label="accessKey" :required="file['config_key'] == 'OSS'" prop="access_key">
                <el-input v-model="file['access_key']" autocomplete="off"></el-input>
                <div class="tip">如果是Minio的话是【账号】</div>
              </el-form-item>
              <el-form-item label="secretKey" :required="file['config_key'] == 'OSS'" prop="secret_key">
                <el-input v-model="file['secret_key']" autocomplete="off"></el-input>
                <div class="tip">如果是Minio的话是【密码】</div>
              </el-form-item>
              <el-form-item label="bucket" :required="file['config_key'] == 'OSS'" prop="bucket_name">
                <el-input v-model="file['bucket_name']" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="文件公共前缀" prop="prefix">
                <el-input v-model="file['prefix']" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="Endpoint" :required="file['config_key'] == 'OSS'" prop="endpoint">
                <el-input v-model="file['endpoint']" autocomplete="off"></el-input>
                <div class="tip">Endpoint的访问地址，如果是自己搭建的Minio，一般是【ip:9000】</div>
              </el-form-item>
              <el-form-item label="是否HTTPS" prop="https">
                <el-select v-model="file['https']" prop="https" :required="file['config_key'] == 'OSS'"
                           placeholder="请选择协议">
                  <el-option value="true" label="true" key=1>是</el-option>
                  <el-option value="false" label="false" key=2>否</el-option>
                </el-select>
                <div class="tip">Endpoint的访问协议</div>
              </el-form-item>
              <el-form-item label="域" prop="region">
                <el-input v-model="file['region']" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="桶权限" :required="file['config_key'] == 'OSS'" prop="access_policy">
                <el-radio-group v-model="file['access_policy']" prop="access_policy" required>
                  <el-radio label="0">私有(访问文件会先转发到本系统)</el-radio>
                  <el-radio label="1">公共(可设置CDN)</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-show="file['access_policy'] == '1'" label="CDN域名" prop="domain">
                <el-input v-model="file['domain']" autocomplete="off"></el-input>
                <div class="tip">记得加上【https://】或者【http://】前缀，尾部不要跟/</div>
              </el-form-item>
            </template>
            <el-form-item style="text-align: right">
              <el-button type="primary" @click="save('file')">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="第三方API设置" name="extend">
        <div class="container">
          <el-form :model="extend" label-position="right" label-width="150px" ref="fileFormRef">
            <el-alert
                type="warning"
                :closable="false"
                show-icon
                style="margin-bottom: 10px; font-size:14px;">
              <p><b>注意：</b>该设置请做好保密不外泄</p>
            </el-alert>
            <el-collapse>
              <!----------百度翻译开始----------->
              <el-collapse-item title="百度翻译" name="1">
                <el-form-item label="启用百度翻译" prop="enable_baidu_trans">
                  <el-switch v-model="extend['enable_baidu_trans']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，可使用百度翻译接口"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_baidu_trans']">
                  <el-form-item label="百度翻译APP ID" :required="extend['enable_baidu_trans']"
                                prop="baidu_trans_app_id">
                    <el-input v-model="extend['baidu_trans_app_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="百度翻译密钥" :required="extend['enable_baidu_trans']"
                                prop="baidu_trans_security_key">
                    <el-input v-model="extend['baidu_trans_security_key']" autocomplete="off"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------百度翻译结束----------->
              <!----------短信配置开始----------->
              <el-collapse-item title="短信配置" name="2">
                <el-form-item label="启用短信验证码" prop="enable_sms_captcha">
                  <el-switch v-model="extend['enable_sms_captcha']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，可发送验证码"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_sms_captcha']">
                  <el-alert
                      type="warning"
                      :closable="false"
                      show-icon
                      style="margin-bottom: 10px; font-size:14px;">
                    <p><b>注意：</b>短信配置请参考:
                      https://sms4j.com，如果没有符合你的短信平台请自行修改代码或者给我提issues我有空就会做兼容，这里只兼容了【阿里云】和【腾讯云】
                    </p>
                  </el-alert>
                  <el-form-item label="模拟发送" prop="sms_mock">
                    <el-switch v-model="extend['sms_mock']"></el-switch>
                    <el-tooltip
                        effect="dark"
                        content="模拟发送将不会真正的触发发送短信，需要到日志查看发送的内容（一般是用在调试开发阶段）"
                        raw-content
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="supplier" :required="extend['enable_sms_captcha']" prop="sms_supplier">
                    <el-select v-model="extend['sms_supplier']" placeholder="选择平台" @change="changePlatform">
                      <el-option v-for="item in sms_platforms" :value="item.supplier" :label="item.name"
                                 :key="item.supplier">{{
                          item.name
                        }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="request-url" prop="sms_request_url">
                    <el-input v-model="extend['sms_request_url']" autocomplete="off"
                              placeholder="该项大多时候不需要设置，除非你设置了中转代理"></el-input>
                  </el-form-item>
                  <el-form-item label="access-key-id" :required="extend['enable_sms_captcha']" prop="sms_access_key_id">
                    <el-input v-model="extend['sms_access_key_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="access-key-secret" :required="extend['enable_sms_captcha']"
                                prop="sms_access_key_secret">
                    <el-input v-model="extend['sms_access_key_secret']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="signature" :required="extend['enable_sms_captcha']" prop="sms_signature">
                    <el-input v-model="extend['sms_signature']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="template-id" prop="sms_template_id">
                    <el-input v-model="extend['sms_template_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="territory" prop="sms_territory">
                    <el-input v-model="extend['sms_territory']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="sdk-app-id" prop="sms_sdk_app_id">
                    <el-input v-model="extend['sms_sdk_app_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="region-id" prop="sms_region_id">
                    <el-input v-model="extend['sms_region_id']" autocomplete="off"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------短信配置结束----------->
              <!----------邮件配置开始----------->
              <el-collapse-item title="邮件配置" name="3">
                <el-form-item label="启用邮件" prop="enable_mail">
                  <el-switch v-model="extend['enable_mail']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，可使用邮件发送验证码或者接收告警"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_mail']">
                  <el-form-item label="模拟发送" prop="mail_mock">
                    <el-switch v-model="extend['mail_mock']"></el-switch>
                    <el-tooltip
                        effect="dark"
                        content="模拟发送将不会真正的触发发送邮件，需要到日志查看发送的内容（一般是用在调试开发阶段）"
                        raw-content
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="启用SSL" :required="extend['enable_mail']" prop="mail_enable_ssl">
                    <el-switch v-model="extend['mail_enable_ssl']"></el-switch>
                    <el-tooltip
                        effect="dark"
                        content="使用 SSL安全连接"
                        raw-content
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="服务器域名" :required="extend['enable_mail']" prop="mail_host">
                    <el-input v-model="extend['mail_host']" autocomplete="off" placeholder="SMTP服务器域名"></el-input>
                  </el-form-item>
                  <el-form-item label="服务器端口" :required="extend['enable_mail']" prop="mail_port">
                    <el-input v-model="extend['mail_port']" autocomplete="off" placeholder="SMTP服务端口"></el-input>
                  </el-form-item>
                  <el-form-item label="需要验证" prop="mail_enable_auth">
                    <el-switch v-model="extend['mail_enable_auth']"></el-switch>
                  </el-form-item>
                  <el-form-item label="用户名" :required="extend['mail_enable_auth']" prop="mail_user">
                    <el-input v-model="extend['mail_user']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="密码" :required="extend['mail_enable_auth']" prop="mail_password">
                    <el-input v-model="extend['mail_password']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="发送方" prop="mail_password">
                    <el-input v-model="extend['mail_from']" autocomplete="off" placeholder="遵循RFC-822标准"></el-input>
                  </el-form-item>
                  <el-form-item label="启用STARTTLS" :required="extend['enable_mail']" prop="mail_enable_starttls">
                    <el-switch v-model="extend['mail_enable_starttls']"></el-switch>
                    <el-tooltip
                        effect="dark"
                        content="使用 STARTTLS安全连接，STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接（TLS或SSL）， 而不是使用一个单独的加密通信端口。"
                        raw-content
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="启用SSL" :required="extend['enable_mail']" prop="mail_enable_ssl">
                    <el-switch v-model="extend['mail_enable_ssl']"></el-switch>
                    <el-tooltip
                        effect="dark"
                        content="使用 SSL安全连接"
                        raw-content
                        placement="right"
                    >
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </el-form-item>
                  <el-form-item label="SMTP超时时间(毫秒)">
                    <el-input v-model="extend['mail_timeout']" autocomplete="off"
                              placeholder="SMTP超时时长，单位毫秒，不配置时候不超时"></el-input>
                  </el-form-item>
                  <el-form-item label="Socket连接超时(毫秒)">
                    <el-input v-model="extend['mail_connection_timeout']" autocomplete="off"
                              placeholder="Socket连接超时值，单位毫秒，不配置时候不超时"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------邮件配置结束----------->
              <!----------支付宝配置开始----------->
              <el-collapse-item title="支付宝配置" name="4">

                <el-form-item label="启用支付宝支付" prop="enable_alipay">
                  <el-switch v-model="extend['enable_alipay']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，用户购买产品可以使用支付宝"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_alipay']">
                  <el-form-item label="通信协议" :required="extend['enable_alipay']"
                                prop="alipay_protocol">
                    <el-input v-model="extend['alipay_protocol']" autocomplete="off"
                              placeholder="通常填写https"></el-input>
                  </el-form-item>
                  <el-form-item label="网关域名" :required="extend['enable_alipay']"
                                prop="alipay_gateway_host">
                    <div class="tip-input-line">
                      <el-input v-model="extend['alipay_gateway_host']" autocomplete="off"></el-input>
                      <div class="tip">线上为：【openapi.alipay.com】沙箱为：【openapi-sandbox.dl.alipaydev.com】</div>
                    </div>
                  </el-form-item>
                  <el-form-item label="AppId" :required="extend['enable_alipay']"
                                prop="alipay_app_id">
                    <el-input v-model="extend['alipay_app_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="签名类型" :required="extend['enable_alipay']"
                                prop="alipay_sign_type">
                    <el-input v-model="extend['alipay_sign_type']" autocomplete="off"
                              placeholder="Alipay Easy SDK只推荐使用RSA2，估此处固定填写RSA2"></el-input>
                  </el-form-item>
                  <el-form-item label="应用私钥" :required="extend['enable_alipay']" prop="alipay_merchant_private_key">
                    <el-input v-model="extend['alipay_merchant_private_key']" autocomplete="off"
                              placeholder="应用私钥(复制应用私钥放在此处)"></el-input>
                  </el-form-item>
                  <el-form-item label="应用公钥证书" :required="extend['enable_alipay']"
                                prop="alipay_merchant_cert_path">
                    <el-input v-model="extend['alipay_merchant_cert_path']" placeholder="应用公钥:appPublicCert.crt">
                      <template #append>
                        <el-upload
                            :auto-upload="true"
                            :show-file-list="false"
                            @click="beforeUpload('alipay_merchant_cert_path')"
                            :http-request="uploadCert"
                        >
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="支付宝公钥证书" :required="extend['enable_alipay']"
                                prop="alipay_alipay_cert_path">
                    <el-input v-model="extend['alipay_alipay_cert_path']"
                              placeholder="支付宝公钥证书:alipayPublicCert.crt">
                      <template #append>
                        <el-upload
                            :auto-upload="true"
                            :show-file-list="false"
                            @click="beforeUpload('alipay_alipay_cert_path')"
                            :http-request="uploadCert"
                        >
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="支付宝根证书" :required="extend['enable_alipay']"
                                prop="alipay_alipay_root_cert_path">
                    <el-input v-model="extend['alipay_alipay_root_cert_path']"
                              placeholder="支付宝根证书:alipayRootCert.crt">
                      <template #append>
                        <el-upload
                            :auto-upload="true"
                            :show-file-list="false"
                            @click="beforeUpload('alipay_alipay_root_cert_path')"
                            :http-request="uploadCert"
                        >
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="异步通知回调地址"
                                prop="alipay_notify_url">
                    <el-input v-model="extend['alipay_notify_url']" autocomplete="off"
                              placeholder="异步通知回调地址（可选）,不填的话只能靠定时任务了，强烈建议填上"></el-input>
                  </el-form-item>
                  <el-form-item label="AES密钥"
                                prop="alipay_encrypt_key">
                    <el-input v-model="extend['alipay_encrypt_key']" autocomplete="off"
                              placeholder="AES密钥（可选）"></el-input>
                  </el-form-item>
                  <el-form-item label="签名提供方的名称"
                                prop="alipay_sign_provider">
                    <el-input v-model="extend['alipay_sign_provider']" autocomplete="off"
                              placeholder="签名提供方的名称(可选)，例：Aliyun KMS签名，signProvider =AliyunKMS"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------支付宝支付结束----------->
              <!----------微信支付开始----------->
              <el-collapse-item title="微信支付配置" name="5">
                <el-form-item label="启用微信支付" prop="enable_wechat_pay">
                  <el-switch v-model="extend['enable_wechat_pay']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，可使用微信支付"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_wechat_pay']">
                  <el-form-item label="AppId" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_app_id">
                    <el-input v-model="extend['wechat_pay_app_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="商户ID" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_mch_id">
                    <el-input v-model="extend['wechat_pay_mch_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="商户密钥" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_mch_key">
                    <el-input v-model="extend['wechat_pay_mch_key']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="商户API V3密钥" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_api_v3_key">
                    <el-input v-model="extend['wechat_pay_api_v3_key']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="PrivateKey" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_private_key">
                    <el-input v-model="extend['wechat_pay_private_key']"
                              placeholder="apiclient_key.pem证书文件的绝对路径">
                      <template #append>
                        <el-upload
                            :auto-upload="true"
                            :show-file-list="false"
                            @click="beforeUpload('wechat_pay_private_key')"
                            :http-request="uploadCert"
                        >
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="PrivateCert" :required="extend['enable_wechat_pay']"
                                prop="wechat_pay_private_cert">
                    <el-input v-model="extend['wechat_pay_private_cert']"
                              placeholder="apiclient_cert.pem证书文件的绝对路径">
                      <template #append>
                        <el-upload
                            :auto-upload="true"
                            :show-file-list="false"
                            @click="beforeUpload('wechat_pay_private_cert')"
                            :http-request="uploadCert"
                        >
                          <el-icon class="uploader-icon">
                            <UploadFilled/>
                          </el-icon>
                        </el-upload>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="异步通知回调地址"
                                prop="wechat_pay_notify_url">
                    <el-input v-model="extend['wechat_pay_notify_url']" autocomplete="off"
                              placeholder="异步通知回调地址（可选）,不填的话只能靠定时任务了，强烈建议填上"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------微信支付结束----------->
              <!----------微信公众号----------->
              <el-collapse-item title="微信公众号配置" name="6">
                <el-form-item label="启用微信微信公众号" prop="enable_wechat_mp">
                  <el-switch v-model="extend['enable_wechat_mp']"/>
                  <el-tooltip
                      effect="dark"
                      content="启用后，可使用微信扫码关注公众号自动登录"
                      raw-content
                      placement="right"
                  >
                    <el-icon>
                      <InfoFilled/>
                    </el-icon>
                  </el-tooltip>
                </el-form-item>
                <template v-if="extend['enable_wechat_mp']">
                  <el-alert
                      type="warning"
                      :closable="false"
                      show-icon
                      style="margin-bottom: 10px; font-size:14px;">
                    <p><b>注意：</b>微信配置的回调URL为【域名/api/wechatMp/notify】</p>
                  </el-alert>
                  <el-form-item label="appID" :required="extend['enable_wechat_mp']"
                                prop="wechat_mp_app_id">
                    <el-input v-model="extend['wechat_mp_app_id']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="appSecret" :required="extend['enable_wechat_mp']"
                                prop="wechat_mp_app_secret">
                    <el-input v-model="extend['wechat_mp_app_secret']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="Token" :required="extend['enable_wechat_mp']"
                                prop="wechat_mp_token">
                    <el-input v-model="extend['wechat_mp_token']" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="AES"
                                prop="wechat_mp_aes_key">
                    <el-input v-model="extend['wechat_mp_aes_key']" autocomplete="off"></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
              <!----------微信支付结束----------->
            </el-collapse>
            <el-form-item style="text-align: right">
              <el-button type="primary" @click="save('extend')">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="系统运维" name="devops">
        <div class="container">
          <el-form :model="devops" label-position="right" label-width="150px" ref="devopsFormRef" :rules="rules">
            <el-alert
                type="warning"
                :closable="false"
                show-icon
                style="margin-bottom: 10px; font-size:14px;">
              <p><b>注意：</b>该设置针对运维相关的操作</p>
            </el-alert>
            <el-form-item label="启用审计日志" prop="enable_audit_logger">
              <el-switch v-model="devops['enable_audit_logger']"/>
              <el-tooltip
                  effect="dark"
                  content="启用后，将会在日志里面打印请求的输入和响应的日志（线上建议关闭）"
                  raw-content
                  placement="right"
              >
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="启用Key失效告警" prop="enable_alert">
              <el-switch v-model="devops['enable_alert']"/>
              <el-tooltip
                  effect="dark"
                  content="启用后，将会在用户请求该key响应失败后发送告警"
                  raw-content
                  placement="right"
              >
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </el-form-item>
            <template v-if="devops['enable_alert']">
              <el-alert
                  type="warning"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 10px; font-size:14px;">
                <p><b>注意：</b>告警方式最少填一个，不填的话不会触发告警，以下信息填错也不会发送告警，请注意输入正确的格式</p>
              </el-alert>
              <el-form-item label="告警间隔" prop="alert_interval">
                <el-input v-model="devops['alert_interval']" autocomplete="off" placeholder="相同的key告警间隔，不填默认10分钟，单位: 分钟" ></el-input>
              </el-form-item>
              <el-form-item label="告警发送邮箱" prop="alert_mail">
                <el-input v-model="devops['alert_mail']" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="告警Webhook" prop="alert_webhook">
                <div class="tip-input-line">
                  <el-input v-model="devops['alert_webhook']" autocomplete="off" placeholder="告警Webhook,记得加http或https前缀"></el-input>
                  <div class="tip">发送方式【POST】,Body数据格式【{"msg":"告警内容"}】</div>
                </div>
              </el-form-item>
            </template>
            <el-form-item style="text-align: right">
              <el-button type="primary" @click="save('devops')">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="公告配置" name="notice">
        <md-editor class="mgb20" v-model="notice" @on-upload-img="onUploadImg"/>
        <el-form-item>
          <el-button type="primary" @click="save('notice')">保存</el-button>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {httpGet, httpPost} from "@/utils/http";
import Compressor from "compressorjs";
import {ElMessage} from "element-plus";
import {InfoFilled, UploadFilled} from "@element-plus/icons-vue";
import MdEditor from "md-editor-v3";
import 'md-editor-v3/lib/style.css';

const activeName = ref('basic')
const system = ref({models: []})
const loading = ref(true)
const systemFormRef = ref(null)
const chatFormRef = ref(null)
const fileFormRef = ref(null)
const models = ref([])
const notice = ref("")
const file = ref({})
const extend = ref({
  alipay_protocol: "https",
  alipay_sign_type: "RSA2"
})
const devops = ref({})
const extendFormRef = ref(null)
const devopsFormRef = ref(null)
onMounted(() => {
  // 加载系统配置
  httpGet('/api/admin/config/get?key=system').then(res => {
    system.value = res.data
  }).catch(e => {
    ElMessage.error("加载系统配置失败: " + e.message)
  })
  // 加载聊天配置
  httpGet('/api/admin/config/get?key=notice').then(res => {
    notice.value = res.data['content']
  }).catch(e => {
    ElMessage.error("公告信息失败: " + e.message)
  })
  // 加载文件配置
  httpGet('/api/admin/config/get?key=file').then(res => {
    file.value = res.data
  }).catch(e => {
    ElMessage.error("获取文件配置失败: " + e.message)
  })
  httpGet('/api/admin/config/get?key=extend').then(res => {
    extend.value = res.data
  }).catch(e => {
    ElMessage.error("获取第三方配置失败: " + e.message)
  })
  httpGet('/api/admin/config/get?key=devops').then(res => {
    devops.value = res.data
  }).catch(e => {
    ElMessage.error("获取运维配置配置失败: " + e.message)
  })
  httpGet('/api/admin/model/list').then(res => {
    models.value = res.data
    loading.value = false
  }).catch(e => {
    ElMessage.error("获取模型失败：" + e.message)
  })

})
const sms_platforms = ref([
  {
    name: "阿里云短信",
    supplier: "ALIBABA",
    request_url: "dysmsapi.aliyuncs.com",
  },
  {
    name: "腾讯云短信",
    supplier: "TENCENT",
    request_url: "sms.tencentcloudapi.com",
  }
])
const changePlatform = (item) => {
  let platform = null
  for (let v of sms_platforms.value) {
    if (v.supplier === item) {
      platform = v
      break
    }
  }
  if (platform !== null) {
    extend.value.sms_request_url = platform.request_url
  }
}
const rules = reactive({
  title: [{required: true, message: '请输入网站标题', trigger: 'blur',}],
  admin_title: [{required: true, message: '请输入控制台标题', trigger: 'blur',}],
  init_chat_calls: [{required: true, message: '请输入赠送对话次数', trigger: 'blur'}],
  user_img_calls: [{required: true, message: '请输入赠送绘图次数', trigger: 'blur'}],
})
const save = function (key) {
  if (key === 'system') {
    systemFormRef.value.validate((valid) => {
      if (valid) {
        system.value['power_price'] = parseFloat(system.value['power_price']) ?? 0
        httpPost('/api/admin/config/update', {key: key, config: system.value}).then(() => {
          ElMessage.success("操作成功！")
        }).catch(e => {
          ElMessage.error("操作失败：" + e.message)
        })
      }
    })
  } else if (key === 'chat') {
    if (chat.value.context_deep % 2 !== 0) {
      return ElMessage.error("会话上下文深度必须为偶数！")
    }
    chatFormRef.value.validate((valid) => {
      if (valid) {
        httpPost('/api/admin/config/update', {key: key, config: chat.value}).then(() => {
          ElMessage.success("操作成功！")
        }).catch(e => {
          ElMessage.error("操作失败：" + e.message)
        })
      }
    })
  } else if (key === 'notice') {
    httpPost('/api/admin/config/update', {key: key, config: {content: notice.value, updated: true}}).then(() => {
      ElMessage.success("操作成功！")
    }).catch(e => {
      ElMessage.error("操作失败：" + e.message)
    })
  } else if (key === 'file') {
    fileFormRef.value.validate((valid) => {
      if (valid) {
        httpPost('/api/admin/config/update', {key: key, config: file.value}).then(() => {
          ElMessage.success("操作成功！")
        }).catch(e => {
          ElMessage.error("操作失败：" + e.message)
        })
      }
    })
  } else if (key === 'extend') {
    fileFormRef.value.validate((valid) => {
      if (valid) {
        httpPost('/api/admin/config/update', {key: key, config: extend.value}).then(() => {
          ElMessage.success("操作成功！")
        }).catch(e => {
          ElMessage.error("操作失败：" + e.message)
        })
      }
    })
  } else if (key === 'devops') {
    fileFormRef.value.validate((valid) => {
      if (valid) {
        httpPost('/api/admin/config/update', {key: key, config: devops.value}).then(() => {
          ElMessage.success("操作成功！")
        }).catch(e => {
          ElMessage.error("操作失败：" + e.message)
        })
      }
    })
  }
}
const configKey = ref("")
const beforeUpload = (key) => {
  configKey.value = key
}
const uploadCert = (file) => {
  const formData = new FormData();
  formData.append('file', file.file, file.name);
  // 执行上传操作
  httpPost('/api/admin/config/uploadCert', formData).then((res) => {
    extend.value[configKey.value] = res.data.url
    ElMessage.success('上传成功')
  }).catch((e) => {
    ElMessage.error('上传失败:' + e.message)
  })
};
// 图片上传
const uploadImg = (file) => {
  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData();
      formData.append('file', result, result.name);
      // 执行上传操作
      httpPost('/api/upload', formData).then((res) => {
        system.value[configKey.value] = res.data.url
        ElMessage.success('上传成功')
      }).catch((e) => {
        ElMessage.error('上传失败:' + e.message)
      })
    },
    error(e) {
      ElMessage.error('上传失败:' + e.message)
    },
  });
};

// 编辑期文件上传处理
const onUploadImg = (files, callback) => {
  Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          const formData = new FormData();
          formData.append('file', file, file.name);
          // 执行上传操作
          httpPost('/api/upload', formData).then((res) => rev(res)).catch((error) => rej(error));
        });
      })
  ).then(res => {
    ElMessage.success({message: "上传成功", duration: 500})
    callback(res.map((item) => item.data.url));
  }).catch(e => {
    ElMessage.error('图片上传失败:' + e.message)
  })


};

</script>

<style lang="stylus" scoped>
@import "@/assets/css/admin/form.styl"
.system-config {
  display flex
  justify-content center

  .el-tabs {
    width 100%
    background-color #ffffff
    padding 10px 20px 40px 20px
    border: 1px solid #ddd;
    border-radius: 5px

    .container {
    .el-form {
      .el-form-item__content {

        .tip-text {
          padding-left 10px;
        }

        .el-icon {
          font-size 16px
          margin-left 10px
          cursor pointer
        }

        .uploader-icon {
          font-size 24px
          position relative
          top 3px
        }

        .tip-input-line {
          .tip {
            margin-top 10px
            color #c1c1c1
            font-size 12px;
            line-height 1.5;
          }
        }
      }
    }

    .el-alert {
      margin-bottom 15px;
    }
  }

  }
}
</style>
